#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
#include <QTimer>
#include <QImage>
#include <QtConcurrent/QtConcurrent>
#include <QFutureWatcher>

QImage loadImage(const QString &uri)
{
    QImage image(uri);
    return image;
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    m_watcher(this),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("Demo_QtConcurrent");
    setFixedSize(1024, 768);
    connect(&m_watcher, &QFutureWatcher<QImage>::finished, this, &MainWindow::onFinished);
    QTimer::singleShot(3000, this, &MainWindow::onLoad);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    if(m_image.isNull())
    {
        painter.drawText(rect(),Qt::AlignCenter, "Loading...");
    }
    else{
        painter.drawImage(rect(), m_image);
    }
}

void MainWindow::onLoad()
{
    QString uri(":/timg.jpg");
    QFuture<QImage> future = QtConcurrent::run(loadImage, uri);
    m_watcher.setFuture(future);
}

void MainWindow::onFinished()
{
    m_image = m_watcher.future().result();
    if(!m_image.isNull())
    {
        repaint();
    }
}
